#include<stdio.h>
#include<pthread.h>

//多个顾客多个厨师
//

int counter=0;  //0-柜台没饭，1-柜台有饭

pthread_mutex_t mutex;  //定义互斥锁
pthread_cond_t cond_cook;  //定义条件变量
pthread_cond_t cond_cus;  //定义条件变量

void* Customer(void* arg){
  while(1){
    pthread_mutex_lock(&mutex);   //首先加锁
    while(counter<=0){  //判断有无饭
      //柜台没有饭，需要阻塞等待----解锁-休眠-被唤醒后加锁
      pthread_cond_wait(&cond_cus,&mutex);
    }
    //否则，counter = 1 有饭
    printf("饭好吃，再来一碗！\n");
    counter--;
    pthread_cond_signal(&cond_cook);  //唤醒厨师做饭
    pthread_mutex_unlock(&mutex);  //解锁
  }
  return 0;
}

void* Cook(void* arg){
  while(1){
    pthread_mutex_lock(&mutex);  //首先加锁
    while(counter>=1){
      //有饭，则阻塞
      pthread_cond_wait(&cond_cook,&mutex);
    }
    //否则，counter = 0 没有饭，需要做饭
    printf("饭好了，快来吃饭！\n");
    counter++;
    pthread_cond_signal(&cond_cus);   //唤醒顾客
    pthread_mutex_unlock(&mutex);  //解锁
  }
  return 0;
}

int main()
{
  //创建两个线程----顾客，厨师
  pthread_t cus_tid[4],cook_tid[4];
  int ret;
  //初始化操作----初始化互斥锁与条件变量
  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cond_cus,NULL);
  pthread_cond_init(&cond_cook,NULL);

  int i=0;
  for(;i<4;++i){
    ret=pthread_create(&cus_tid[i],NULL,Customer,NULL);
    if(ret!=0){
      perror("pthread_create error!\n");
      return -1;
    }
  }

  for(i=0;i<4;++i){
    ret=pthread_create(&cook_tid[i],NULL,Cook,NULL);
    if(ret!=0){
      perror("pthread_create error!\n");
      return -1;
    }
  }

  //线程等待-----等待任意固定线程退出
  pthread_join(cus_tid[0],NULL);
  pthread_join(cook_tid[0],NULL);


  //销毁
  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond_cus);
  pthread_cond_destroy(&cond_cook);

  return 0;
}
